import os
import re
import sys
from xml.dom import minidom

def expandEnvVarInPath(path) :
    envVarGroup = re.compile(r'\$\(([^)]*)\)')

    while re.search(envVarGroup, path) :
        curvariable = re.search(envVarGroup, path).group(0)
        tmp = os.path.expandvars(re.sub(envVarGroup, r"${\1}", curvariable))
        tmp2 = ""
        for x in tmp:
            if x == '\\' : tmp2 += '\\'
            tmp2 += x
        path = re.sub(envVarGroup, tmp2, path, 1)

    return path


def getAllProjFiles(filename) :
    if not os.path.isfile(filename) : 
        return []
    dom = minidom.parse(filename)
    nodelist = dom.getElementsByTagName('ClCompile')
    nodelist.extend(dom.getElementsByTagName('ClInclude'))

    nodelist = [x.getAttribute("Include") for x in nodelist]
    nodelist = filter(lambda x : not x == "", nodelist)
    nodelist = [expandEnvVarInPath(x) for x in nodelist]

    curpath = os.path.dirname(filename)
    nodelist = [os.path.normpath(os.path.join(curpath, x)).lower() for x in nodelist]

    for x in nodelist:
        if not os.path.isfile(x) : 
            print "can't find " + x

    if nodelist :
        nodelist.sort()
        last = nodelist[-1]
        for i in range(len(nodelist) - 2, -1, -1) :
                if last == nodelist[i] : 
                        print "found duplicate file " + last
                        del nodelist[i]
                else :
                        last = nodelist[i]
    
    return nodelist
    



rootPath = r'u:\desktop\source'

Paths = [rootPath]
Files = []
for curpath in Paths :
    templist = os.listdir(curpath)
    templist = [(os.path.join(curpath, x)).lower() for x in templist]
    temppathlist = [x for x in templist if os.path.isdir(x)]
    tempfilelist = [x for x in templist if os.path.isfile(x)]
    Paths.extend(temppathlist)
    Files.extend(tempfilelist)

vcxprojlist = [x for x in Files if os.path.splitext(x)[1] == ".vcxproj"]
vcxprojlist.sort()

#remove negligible files
Files = filter(lambda x : not os.path.splitext(x)[1] in [".bat", ".filters", ".txt", ".pch", ".vcxproj", ".xcconfig", ".user"], Files)
Files = [unicode(x, errors='ignore') for x in Files]
Files.sort()

#vcxprojlist = [r"u:\desktop\source\crx\aecarchcore\aecarchcore.vcxproj"]
setFiles = set(Files)
for x in vcxprojlist:
    print "start     " + x
    curprojfiles = set(getAllProjFiles(x))
    print "end       " + x
    print 
    print
    setFiles = setFiles.difference(curprojfiles)
    
print
print
print "files not in any projects : "
for x in setFiles :
    print x
print "end"

print "well done!!!"
    

    